/**
 * abssqr.com Inc.
 * Copyright (c) 2017-2019 All Rights Reserved.
 */
package cn.dalgen.mybatis.gen.model.repository.db.database;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

import cn.dalgen.mybatis.gen.model.repository.db.database.proxy.InvocationHandlerImpl;
import cn.dalgen.mybatis.gen.utils.ConfigUtil;
import org.apache.commons.lang.StringUtils;

/**
 * @author bangis.wangdf
 * @version cn.dalgen.mybatis.gen.model.repository.db.database: DataBaseInfoHandler.java, v 0.1 2019-04-23 16:39
 * bangis.wangdf Exp $
 */
public class DataBaseInfoHandler {
    private static Map<String, DataBaseInfoService> dataBaseInfoServiceMap = new HashMap<>();

    static {
        proxy("mysql",new MySqlDataBaseInfoService());
        proxy("postgresql",new OracleDataBaseInfoService());
        proxy("oracle",new OracleDataBaseInfoService());
    }

    private static void proxy(String key,DataBaseInfoService dataBaseInfoService) {
        InvocationHandler handler = new InvocationHandlerImpl(dataBaseInfoService);
        ClassLoader loader = dataBaseInfoService.getClass().getClassLoader();
        Class[] interfaces = dataBaseInfoService.getClass().getInterfaces();
        /**
         * 该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例
         */
        DataBaseInfoService subject = (DataBaseInfoService) Proxy.newProxyInstance(loader, interfaces, handler);
        dataBaseInfoServiceMap.put(key, subject);
    }

    public static DataBaseInfoService getDataBaseInfoService() {
        return dataBaseInfoServiceMap.get(StringUtils.lowerCase(ConfigUtil.getCurrentDb().getType()));
    }
}
